"use strict"

//处理登录页面的逻辑
const fs=require("fs");
const captchapng=require("captchapng");

exports.getLoginPage=function(req,res){
	// console.log(req);
	/**
	 * 1.读取views下面的login.html
	 * 2.利用res.end()返回给浏览器
	 */
	fs.readFile("./views/login.html", (err,content)=>{
		res.end(content);
	})
	console.log(1);
}
//处理登录逻辑
/**
 获取从浏览器传过来的参数
 验证验证码
 验证码正确则继续执行,不正确,则提醒用户重新输入
 进行密码账户验证,如果有则说明合法用户啊,反之,则密码,用户名错误
 */
exports.login=(req,res,next)=>{
	console.log(1);
	// console.log(req.body);
	// 获取浏览器传过来的参数
 	const name = req.body.uname;
 	const pas = req.body.upwd;
  const vcode = req.body.vcode;
  //验证验证码是否正确.
  if(vcode!=req.session.vcode){
  	res.end("<script>alert('验证码错误!!!');window.location.href='/account/login';</script>");
  	return ;
  }
  //操作数据库,查看数据库中是否有用户登录的匹配
	req.models.user.find({name:name,pasw:pas},(err,users)=>{
		// console.log(users);
		if(err){
			console.log(err);
			return;
		}
		res.setHeader("Content-Type","text/html;charset=utf-8");
		if(users != null && users.length == 1){
			//登录成功之后,存贮用户名,
			req.session.name = name;
      //删除session中的验证码
      req.session.vcode = null;
			res.end("<script>alert('恭喜你,登录成功');window.location.href='/video/list';</script>");

		}else{
			res.end("<script>alert('用户名和密码错误!!!');window.location.href='/account/login';</script>");
		}
	});
}
//生成验证码
exports.getVCode=(req,res)=>{
		//生成验证码
		const vcode=parseInt(Math.random()*9000+1000);
		//将验证码存储在session中.
		req.session.vcode =vcode;
		var p = new captchapng(80,30,vcode); // width,height,numeric captcha 
    p.color(0, 0, 0, 0);  // First color: background (red, green, blue, alpha) 
    p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha) 

    var img = p.getBase64();
    var imgbase64 = new Buffer(img,'base64');
    res.writeHead(200, {
        'Content-Type': 'image/png'
    });
    res.end(imgbase64);
}
//退出登录
exports.logout=(req,res)=>{
	//清空session中用户状态的值
	req.session.name = null;
	res.setHeader("Content-Type","text/html;charset=utf-8");
	res.end("<script>window.location.href='/account/login';</script>");
}